//
//  ChoseAddressViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/4/14.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ChoseAddressViewController.h"
#import "ChoseAddressTableViewCell.h"
#import "AddAddressViewController.h"
static NSString * questionCellIndentfier = @"ChoseAddressTableViewCell";

@interface ChoseAddressViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray * addressArray;

@end

@implementation ChoseAddressViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // 马上进入刷新状态
    [_addressArray removeAllObjects];
    [self.tableView.header beginRefreshing];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    _addressArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}
#pragma mark  布局调整--=========================================
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:questionCellIndentfier bundle:nil] forCellReuseIdentifier:questionCellIndentfier];
    
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getAddressList];
        });
    }];
   
}
//加载更多数据
- (void)loadMoreData{
    if (self.addressArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getAddressList];
        });
    }
    
}


- (void)getAddressList{
   
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
     NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"page"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMallShippingAddress withHttpType:@"POST" withTag:HK_HK_queryMallShippingAddress];
}

- (IBAction)addAddress:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
    [[Common getNavigation]pushViewController:page];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 130*VerticalRatio();
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _addressArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    ChoseAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:questionCellIndentfier];
    if (cell == nil) {
        cell= [[ChoseAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:questionCellIndentfier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSDictionary * dic = _addressArray[indexPath.row];
    cell.nameLabel.text = dic[@"msadReceiverName"];
    cell.phoneNumber.text = dic[@"msadMobileNo"];
    cell.address.text = [NSString stringWithFormat:@"%@%@%@%@",dic[@"msadProvinceName"],dic[@"msadCityName"],dic[@"msadAreaName"],dic[@"msadAddr"]];
    
    cell.edit = ^(NSInteger index){
    
        if (index==1) {
            UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
            AddAddressViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AddAddress"];
            page.addressInfo = [_addressArray[indexPath.row] mutableCopy];
            page.endEditBlock = ^(NSString * str){};
            [[Common getNavigation]pushViewController:page];
        }
    
    };
    
    
    return cell;
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self backBtn];
    _choseAddress(_addressArray[indexPath.row]);
    
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
   
    if (tag==HK_HK_queryMallShippingAddress) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
//            dispatch_async(dispatch_get_main_queue(), ^{
//                _totle = [database[@"result"][@"totalResults"] integerValue];
//                if (_totle > PageSize) {
//                    __weak __typeof(self) weakSelf = self;
//                    if (!self.tableView.footer) {
//                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
//                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//                            [weakSelf loadMoreData];
//                        }];
//                    }
//                }
//                if (self.pageNO == 1) {
//                    [self.addressArray removeAllObjects];
//                }
                NSArray *arr = database[@"result"];
                for (id entity in arr) {
                    [self.addressArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
//            });

        }
        
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
